import csv
from random import randint, choice
from datetime import datetime, timedelta
# 生成模拟数据
def generate_mock_data(num_entries):
    users = ["user1", "user2", "user3", "user4", "user5"]
    categories = ["electronics", "books", "clothing", "home", "sports", "beauty","toys"]
    data = []
    start_date = datetime.strptime("2025-01-01", "%Y-%m-%d")
    for i in range(num_entries):
       user = choice(users)
       category = choice(categories)
       rating = randint(1, 5)
       date = (start_date + timedelta(days=randint(0, 364))).strftime("%Y-%m-%d")
       data.append((user, category, rating, date))
    return data
# 生成100条模拟数据
mock_data = generate_mock_data(100)
# 添加原始的前3条数据
original_data = [
        ("user1", "electronics", 5, "2025-01-01"),
        ("user2", "books", 3, "2025-01-02"),
        ("user1", "books", 4, "2025-01-03"),
]
mock_data = original_data + mock_data
# 导出为CSV文件
csv_filename = "user_reviews.csv"
with open(csv_filename, mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["user_id", "category", "rating", "date"]) # 写入标题
    writer.writerows(mock_data)
print(f"数据已导出到 {csv_filename}")
# 从CSV文件读取数据
def read_csv_data(filename):
   data = []
   with open(filename, mode='r') as file:
        reader = csv.reader(file)
        next(reader) # 跳过标题行
        for row in reader:
        # 将rating转换为整数
            row[2] = int(row[2])
            data.append(tuple(row))
   return data
# 读取CSV文件
loaded_data = read_csv_data(csv_filename)
# 打印前5条数据作为示例
print("\n从CSV文件读取的前5条数据:")
for i, row in enumerate(loaded_data[:5], 1):
    print(f"{i}. {row}")
print(f"\n总共读取了 {len(loaded_data)} 条数据")